<?php

/*
 * This file will perform the ajax for sending an attachment.
 * The following tables will be inserted or updated with data :
 * Attachment
 * ExternalAccount
 * Sent_Attachment
 * Log
 * 
 * Created by: Peter Agno Jr.
 * Date created: Octber 17, 2011
 * 
 * In parameters: receiverType, departmentId, positionId, sendToIptBx, attachmentId, scrnPostn
 * Out parameters: transacFlag
 */

session_start();

// Start - Checker for those users who will just go to the page by typing directly in the url.
if ($_POST) { 
    include('../includes/siteConfig.php'); 

    // connect to database
    $connect = mysql_connect($hostName,$rootName,$dBasePassword) or die ('Unable to connect!');
    mysql_select_db($dBaseName) or die ('Unable to select database!');

    $receiverType = $_POST['receiverType'];
    $attachmentId = $_POST['attachmentId'];
    $scrnPostn = $_POST['scrnPostn'];
    
    // ############ Start - Here are the same data that will be used either Internal or External ############
        // Get first the currentStepId of the attachment's main document
        $currentStepId = "";
        $query =
            "
                SELECT currentStepId
                FROM MainDocument as MD, Attachment as A
                WHERE MD.mainDocumentId = A.mainDocumentId AND A.attachmentId = '$attachmentId'
            ";

        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());

        if (mysql_num_rows($result) > 0) {
            $row = mysql_fetch_array($result);
            $currentStepId = $row['currentStepId'];
        }
    
        // Get userId which will be the sender
        $userId = $_SESSION['loggedUserId'];
        
        // Get current date and time
        date_default_timezone_set('Asia/Singapore');
        $currentDateTime= date("Y-m-d H:i:s" , time());
    // ############ End - Here are the same data that will be used either Internal or External ############
        
    //********************************************************************************************************
    /*
     * Define the functions in here
     */

    // Start function - add data in the Log table that the document was Detached
    function logDetached($attachmentId, $userId, $currentStepId, $currentDateTime) {
        // Insert data in Log
        $query =
            "
                INSERT INTO Log (logId, documentId, userId, stepId, logDateTime, activity) VALUES
                    ('', '$attachmentId', '$userId', '$currentStepId', '$currentDateTime', 'Detached');
            ";

        mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
    } // End function - add data in the Log table that the document was Detached
    //********************************************************************************************************

    switch ($receiverType) {
        case "Internal":
            // Add data and/or update the associated tables if it is internal
            
            $departmentId = $_POST['departmentId'];
            $positionId = $_POST['positionId'];

            // Get the deptPosId for the receiver since this is a position based sent attachment
            $deptPosId = "";
            $query =
                "
                    SELECT DP.deptPosId as deptPosId, D.departmentName as departmentName, P.positionName as positionName
                    FROM Department_Position AS DP, Department as D, Position as P
                    WHERE DP.departmentId = D.departmentId
                        AND DP.positionId = P.positionId
                        AND DP.departmentId = '$departmentId' AND DP.positionId = '$positionId'
                ";
            
            $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
            $row = mysql_fetch_array($result);
            $deptPosId = $row['deptPosId'];
            $departmentName = $row['departmentName'];
            $positionName = $row['positionName'];

            // Insert data in Sent_Attachment
            $query =
                "
                    INSERT INTO Sent_Attachment (documentId, senderId, receiverId, receiveFlag, orgFlag) VALUES
                        ('$attachmentId', '$userId', '$deptPosId', 'Pending', 'Internal');
                ";
            
            mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
            
            // Insert merged in logs if the $scrnPostn is fromTheatre
            if ( $scrnPostn == "fromTheatre" ) {
                logDetached($attachmentId, $userId, $currentStepId, $currentDateTime);
            }
            
            // Insert data in Log
            $query =
                "
                    INSERT INTO Log (logId, documentId, userId, stepId, logDateTime, activity) VALUES
                        ('', '$attachmentId', '$userId', '$currentStepId', '$currentDateTime', 'Sent');
                ";
            
            mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
            
            // Update mainDocumentId of the attachment, make it to NULL since it will be sent
//            $query =
//                "
//                    UPDATE Attachment
//                    SET mainDocumentId = null
//                    WHERE attachmentId = '$attachmentId'
//                ";
//            
//            mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
            
            $feed['transacFlag'] = "Success";
            $feed['msg'] = $attachmentId." was successfully sent to the ".$positionName." of ".$departmentName." department.";
            $feed['receiverType'] = "Internal";
            $feed['exAccName'] = "";
            break;
        
        default:
            // Add data and/or update the associated tables if it is external
            
            // External Receiver Name
            $extRcvrName = $_POST['sendToIptBx'];
            
            // If $extRcvrNamee has no data in ExternalAccount, then add data
            $query =
                "
                    SELECT *
                    FROM ExternalAccount
                    WHERE exAccName = '$extRcvrName'
                ";
            
            $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
    
            if (mysql_num_rows($result) == 0) {
                // Add data
                $query =
                    "
                        INSERT INTO ExternalAccount (exAccId, exAccName) VALUES
                            ('', '$extRcvrName');
                    ";
                
                mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
                
                // Get the exAccId
                $query =
                    "
                        SELECT *
                        FROM ExternalAccount
                        WHERE exAccName = '$extRcvrName'
                    ";
                
                $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
                $row = mysql_fetch_array($result);
                $exAccId = $row['exAccId'];
            }
            else {
                // Get the exAccId
                $row = mysql_fetch_array($result);
                $exAccId = $row['exAccId'];
            }
            // You now have the $exAccId
            
            // Insert data in Sent_Attachment
            $query =
                "
                    INSERT INTO Sent_Attachment (documentId, senderId, receiverId, receiveFlag, orgFlag) VALUES
                        ('$attachmentId', '$userId', '$exAccId', 'Pending', 'External');
                ";
            
            mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
            
            // Insert merged in logs if the $scrnPostn is fromTheatre
            if ( $scrnPostn == "fromTheatre" ) {
                logDetached($attachmentId, $userId, $currentStepId, $currentDateTime);
            }
            
            // Insert data in Log
            $query =
                "
                    INSERT INTO Log (logId, documentId, userId, stepId, logDateTime, activity) VALUES
                        ('', '$attachmentId', '$userId', '$currentStepId', '$currentDateTime', 'Sent');
                ";
            
            mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
            
            // Update mainDocumentId of the attachment, make it to NULL since it will be sent
//            $query =
//                "
//                    UPDATE Attachment
//                    SET mainDocumentId = null
//                    WHERE attachmentId = '$attachmentId'
//                ";
//            
//            mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
            
            $feed['transacFlag'] = "Success";
            $feed['msg'] = $attachmentId." was successfully sent to ".$extRcvrName.".";
            $feed['receiverType'] = "External";
            $feed['exAccName'] = $extRcvrName;
    }
    
    echo json_encode($feed);
    mysql_free_result($result);
    mysql_close($connect);
}   // End - Checker for those users who will just go to the page by typing directly in the url.
else {
    echo "You are not authorized to view this page. This incident will be reported immediately.";
}
?>
